package threadUtils.demo04;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 实现TryLock，和用AtomicBoolean实现的功能是一致的
 */
public class SemaphoreExample02 {

    public static void main(String[] args) {
        TryLock tryLock = new TryLock();

        new Thread(() -> {

            if (!tryLock.lock()) {
                System.out.println(Thread.currentThread().getName() + " is locked");
            }
            try {
                waitLock();
            } finally {
                tryLock.unLock();
            }
        }).start();

        if (!tryLock.lock()) {
            System.out.println(Thread.currentThread().getName() + " is locked");
        } else {
            try {
                waitLock();
            } finally {
                tryLock.unLock();
            }
        }
    }

    private static void waitLock() {
        System.out.println("get the lock");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class TryLock {

    private final Semaphore semaphore = new Semaphore(1, true);

    public boolean lock() {
        return semaphore.tryAcquire();
    }

    public void unLock() {
        System.out.println("release the lock");
        semaphore.release();
    }
}